/**
 * Created by cql-cql-cql on 2017/6/6 0006.
 */

const workModel = require('../model/homework')

const showAllWork = async (ctx, next) => {
        try {
            let conditions = {}, select = {};
            let query = ctx.request.query;
            if (query.conditions) {
                conditions = JSON.parse(query.conditions);
            }
            let builder = workModel.find(conditions);
            if (query.select) {
                select = JSON.parse(query.select);
                builder = builder.select(select);
            }

            ['limit', 'skip', 'sort', 'count'].forEach((key) => {
                if (query[key]) {
                    let value = query[key];
                    if (key == 'limit' || key == 'skip') {
                        value = parseInt(value);
                    }
                    if (key == 'sort') {
                        value = JSON.parse(value)
                    }
                    if (key != 'count') {
                        builder[key](value);
                    } else {
                        builder[key]();
                    }
                }
            })
            let result = await builder.exec();
            return ctx.body = { status : 'ok', data : result};
        } catch (e) {
            return ctx.body = { status : 'fail', data : e.message};
        }

};

const insertWork = async (ctx, next) => {
  /*  let entity = new workModel(ctx.request.body);
    let res= await entity.save();
    ctx.body = res;*/
    try {
        let result = await workModel.create(ctx.request.body);
        ctx.status = 201;
        return ctx.body = { status : 'ok', data : result};
    } catch (e) {
        return ctx.body = { status : 'fail', data : e.message};
    }

};
const deltWork = async (ctx, next) => {
   try{
       let id = ctx.request.body._id;
       await workModel.findOneAndRemove({_id: id});
       ctx.status = 200;
       ctx.body = {
           status: 'ok',
           success: '删除成功'
       };
   }catch(e) {
       return ctx.body = { status : 'fail', data : e.message};
   }
};

const updateById = async function (ctx, next) {
    try {
        let result = await model.findByIdAndUpdate(ctx.params.id, ctx.request.body, {new : true}).exec();
        return ctx.body = { status : 'ok', data : result};
    } catch (e) {
        return ctx.body = { status : 'fail', data : e.message};
    }
}


module.exports = {
    showAllWork,
    insertWork,
    deltWork,
};